/*
 * @Author: AiLjx
 * @Date: 2022-06-28 21:13:11
 * @LastEditors: AiLjx
 * @LastEditTime: 2022-06-29 20:49:27
 */
const express = require("express");
const { buildSchema } = require("graphql");
const graphqlHttp = require("express-graphql");
// 在sercer目录下打开终端，nodemon .\03-mutation.js启动

// 查询使用query，修改数据使用Mutation
// createFilm(input: FilmInput):Film, 获取FilmInput类型的参数，返回Film类型的值
// updateFilm(id:Int!,input:FilmInput):Film, id必填
// deleteFilm(id:Int!):Int
var Scchema = buildSchema(`

   type Film{
       id:Int,
       name:String,
       poster:String,
       price:Int
   }

   input FilmInput{
        name:String,
        poster:String,
        price:Int
   }

   type Query{
       getNowplayingList:[Film]
    }

    type Mutation{
        createFilm(input: FilmInput):Film,
        updateFilm(id:Int!,input:FilmInput):Film,
        deleteFilm(id:Int!):Int
    }
`);

var faskeDb = [
    {
        id: 1,
        name: "1111",
        poster: "http://1111",
        price: 100,
    },
    {
        id: 2,
        name: "2222",
        poster: "http://2222",
        price: 200,
    },
    {
        id: 3,
        name: "3333",
        poster: "http://333",
        price: 300,
    },
];
//处理器
const root = {
    // 查
    getNowplayingList() {
        return faskeDb;
    },
    // 增，这里只是模拟数据库操作
    createFilm({ input }) {
        var obj = { ...input, id: faskeDb.length + 1 };

        faskeDb.push(obj);
        return obj;
    },
    // 改
    updateFilm({ id, input }) {
        console.log(id, input);
        var current = null;
        faskeDb = faskeDb.map((item) => {
            if (item.id === id) {
                current = { ...item, ...input };
                return { ...item, ...input };
            }

            return item;
        });

        return current;
    },
    // 删
    deleteFilm({ id }) {
        faskeDb = faskeDb.filter((item) => item.id !== id);

        return 1;
    },
};

var app = express();
app.use(
    "/graphql",
    graphqlHttp({
        schema: Scchema,
        rootValue: root,
        graphiql: true,
    })
);

app.listen(3001);

// 测试createFilm增
// mutation {
//     createFilm(input:{
//       name:"999",
//       poster:"aaa",
//       price:400 //传的值
//     }) {
//       id,
//       price  // 指定需要返回哪些字段
//     }
//   }
